/**
 * 订单核心数据概览
 * @author hanzhichen (hanzhichen@baijia.com)
 * @date 2021-03-02
 */

import {useState, useCallback, useEffect} from 'react';
import {useRequest} from 'ahooks';
import moment from 'moment';
import {Card} from 'antd';
import {
    querySelectOptions,
    queryValues,
} from '~/service/refundReport';
import {
    queryR4Line,
} from '~/service/specialClass';
import SearchForm from '../common/CommonSearchBar';
import {convertSearcherParams, formatRangePickerValue, addDashBoardIdToDimensionAndValues} from '../common/utils';
import OrderChartCard from './OrdersChartCard';
import OrderDaylyTableCard from './OrderDaylyTableCard';
import OrderUserTableCard from './OrderUserTableCard';
import {searchFormCfg, dashBoardsCfg, selectUnitId} from './config';
import './index.styl';


// 设置默认时间
// const current = new Date();
const initValues = {
    // eslint-disable-next-line babel/camelcase
    // order_dt: [moment(current).subtract(30, 'days'), moment(current)]
};
const initPageInfo = {
    pageNum: 1,
    pageSize: 10
};
const formItemLayout = {
    labelCol: {span: 6},
    wrapperCol: {span: 18}
};
const tailLayout = {
    wrapperCol: {span: 24}
};
const formatDateSearchValue = formatRangePickerValue('YYYYMMDD');
const convertParams = params => {
    // 转换参数
    const {order_dt: OrderDate, ...rest} = params || {};
    let newSearcherParams = params;
    if (OrderDate == null) {
        newSearcherParams = rest;
    } else {
        const formattedOrderDate = formatDateSearchValue(OrderDate);
        newSearcherParams = {
            // eslint-disable-next-line babel/camelcase
            order_dt: formattedOrderDate,
            ...rest
        };
    }
    const queryParams = convertSearcherParams(newSearcherParams);
    return queryParams;
};
const OrderOfflineData = props => {
    // searchform
    // 按钮loading
    const [loading, setLoading] = useState(false);
    const [selectOptions, setSelectOptions] = useState({});
    const [dimensionAndValues, setDimensionAndValues] = useState(
        convertParams(initValues)
    );
    const getDimensionAndValuesForPart3 = dimensionAndValues => {
        const idx = dimensionAndValues?.findIndex(
            item => item.dimensionName === 'order_dt'
        );
        if (idx === -1) {
            return dimensionAndValues || [];
        }
        const orderDtItem = dimensionAndValues[idx];
        const {dimensionId = '', dimensionName = '', value = []} = orderDtItem;
        const newValue =
            value?.length > 0
                ? value.map(item => moment(item, 'YYYYMMDD').format('YYYY-MM-DD'))
                : [];
        const paidTimeItem = {
            dimensionId: 'paid_time',
            dimensionName: 'paid_time',
            value: newValue
        };
        const dimensionAndValues1 = dimensionAndValues.slice();
        dimensionAndValues1.splice(idx, 1, paidTimeItem);
        return dimensionAndValues1;
    };

    // chart查询方法
    const {data: data1, loading: loading1, run: run1} = useRequest(
        queryR4Line,
        {
            manual: true,
            formatResult(res) {
                return res?.data;
            }
        }
    );
    const {data: data2, loading: loading2, run: run2} = useRequest(
        queryValues,
        {
            manual: true,
            formatResult(res) {
                return {data: res?.data, pager: res?.pager};
            }
        }
    );
    const {data: data3, loading: loading3, run: run3} = useRequest(
        queryValues,
        {
            manual: true,
            formatResult(res) {
                return {data: res?.data, pager: res?.pager};
            }
        }
    );

    const [chartData, setChartData] = useState();
    const [tableData1, setTableData1] = useState();
    const [tableData2, setTableData2] = useState();
    const [pageInfo1, setPageInfo1] = useState(initPageInfo);
    const [pageInfo2, setPageInfo2] = useState(initPageInfo);

    useEffect(() => {
        setChartData(data1);
    }, [data1]);
    useEffect(() => {
        setTableData1(data2);
    }, [data2]);
    useEffect(() => {
        setTableData2(data3);
    }, [data3]);

    useEffect(() => {
        setLoading(loading1 || loading2 || loading3);
    }, [loading1, loading2, loading3]);

    const handleTableChange1 = (pagination, filters, sorter, {action}) => {
        if (action === 'sort') {
            // 前端排序
            return;
        }
        const newPageInfo = {
            ...pageInfo1,
            pageNum: pagination?.current ?? 1,
            pageSize: pagination?.pageSize ?? 10
        };
        setPageInfo1(newPageInfo);
        const params2 = {
            dashBoardList: [dashBoardsCfg[1]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                dimensionAndValues,
                dashBoardsCfg[1].dashBoardId
            ),
            pager: newPageInfo
        };
        run2(params2);
    };
    const handleTableChange2 = (pagination, filters, sorter, {action}) => {
        if (action === 'sort') {
            // 前端排序
            return;
        }
        const newPageInfo = {
            ...pageInfo2,
            pageNum: pagination?.current ?? 1,
            pageSize: pagination?.pageSize ?? 10
        };
        setPageInfo2(newPageInfo);
        const params3 = {
            dashBoardList: [dashBoardsCfg[2]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                getDimensionAndValuesForPart3(dimensionAndValues),
                dashBoardsCfg[2].dashBoardId
            ),
            pager: newPageInfo
        };
        run3(params3);
    };

    /** 点击搜索按钮 */
    const handleSearch = useCallback(params => {
        const newDimensionAndValues = convertParams(params);
        setDimensionAndValues(newDimensionAndValues);
        const params1 = {
            dashBoardList: [dashBoardsCfg[0]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                newDimensionAndValues,
                dashBoardsCfg[0].dashBoardId
            ),
        };
        const params2 = {
            dashBoardList: [dashBoardsCfg[1]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                newDimensionAndValues,
                dashBoardsCfg[1].dashBoardId
            ),
            pager: initPageInfo
        };
        const params3 = {
            dashBoardList: [dashBoardsCfg[2]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                getDimensionAndValuesForPart3(newDimensionAndValues),
                dashBoardsCfg[2].dashBoardId
            ),
            pager: initPageInfo
        };
        setPageInfo1(initPageInfo);
        setPageInfo2(initPageInfo);
        run1(params1);
        run2(params2);
        run3(params3);
    }, []);

    /** 点击重置 */
    const handleReset = useCallback(() => {
        const newDimensionAndValues = convertParams(initValues);
        setDimensionAndValues(newDimensionAndValues);
        setChartData();
        setTableData1();
        setTableData2();
        setPageInfo1(initPageInfo);
        setPageInfo2(initPageInfo);
    }, []);

    // 请求单个表单配置项
    const handleFetchOptions = useCallback(
        ({
            key,
            searchKey,
            pager,
            dependItemKey,
            dependItemValue,
            isGetingMore,
            options: curOptions,
            fieldsValue
        }) => {
            let permissions = searchFormCfg.map(item => {
                if (item.key === 'order_dt') {
                    // return {
                    //     dimensionId: `${selectUnitId}_${item.key}`,
                    //     dimensionName: item.key,
                    //     filterItems: fieldsValue?.[item.key]
                    //         ? formatDateSearchValue(fieldsValue[item.key])
                    //         : []
                    // };
                    return {
                        dimensionId: `${selectUnitId}_${item.key}`,
                        dimensionName: item.key,
                        filterItems: [],
                    };
                }
                return {
                    dimensionId: `${selectUnitId}_${item.key}`,
                    dimensionName: item.key,
                    filterItems: Array.isArray(fieldsValue[item.key])
                        ? fieldsValue[item.key]
                        : fieldsValue[item.key] == null
                            ? []
                            : [fieldsValue[item.key]]
                };
            });

            permissions = permissions.filter(item => item.filterItems?.length);

            const params = {
                pager,
                dimensionId: `${selectUnitId}_${key}`,
                dimensionName: key,
                searchKey,
                permissions,
                unitId: selectUnitId
            };

            querySelectOptions(params).then(res => {
                const {data, pager} = res;
                let options =
                    data.map(item => ({
                        key: item,
                        value: item,
                        label: item
                    })) || [];
                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }
                setSelectOptions({key, options, pager});
            });
        },
        []
    );

    return (
        <Card title="订单明细" className="special-class-orders">
            <SearchForm
                noCache
                formItemLayout={formItemLayout}
                tailLayout={tailLayout}
                labelAlign="left"
                config={searchFormCfg}
                selectOptions={selectOptions}
                initialValues={initValues}
                onOk={handleSearch}
                onReset={handleReset}
                onfetchOptions={handleFetchOptions}
                loading={loading}
            />
            <OrderChartCard
                loading={loading1}
                dashBoard={dashBoardsCfg[0]}
                unitId={dashBoardsCfg[0].unitId}
                data={chartData}
                dimensionAndValues={dimensionAndValues}
            />
            <OrderDaylyTableCard
                loading={loading2}
                dashBoard={dashBoardsCfg[1]}
                unitId={dashBoardsCfg[1].unitId}
                tableData={tableData1}
                pageInfo={pageInfo1}
                onTableChange={handleTableChange1}
                dimensionAndValues={dimensionAndValues}
            />
            <OrderUserTableCard
                loading={loading3}
                dashBoard={dashBoardsCfg[2]}
                unitId={dashBoardsCfg[2].unitId}
                tableData={tableData2}
                pageInfo={pageInfo2}
                onTableChange={handleTableChange2}
                dimensionAndValues={getDimensionAndValuesForPart3(dimensionAndValues)}
            />
        </Card>
    );
};

export default OrderOfflineData;
